import { createVNode, reactive } from 'vue'
import { Modal, message } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'

/**
 * @param {
 *    editor: '编辑器',
 *    viewer: '查看器',  
 *    selectedKeys: '选中的数据的KEY集',
 *    deleteService: 'api服务 - 册除',
 *    confirmService: 'api服务 - 确认',
 *    auditService: 'api服务 - 审核批准approve / 拒绝reject',
 * } options
 * @returns
 */
export default function (options = {}) {
  const { deleteService, confirmService, pageAction } = options
  // 审批意见
  const auditState = reactive({ action: 'approve', reason: '', selectedKeys: [] })

  // 新增事件
  const addEvent = () => {
    options.editor.InitializeData()
  }

  // 查看
  const viewEvent = (key) => {
    options.viewer.InitializeData(key)
  }

  // 编辑
  const editEvent = (id) => {
    if(id == undefined) {
      if (options.selectedKeys.length == 1) {
        options.editor.InitializeData(options.selectedKeys[0])
      } else {
        message.warning('只能选中一项进行编辑')
      }
    }else{
      options.editor.InitializeData(id)
    }
  }

  // 删除
  const deleteEvent = () => {
    if (options.selectedKeys.length > 0) {
      Modal.confirm({
        title: '删除确认?',
        icon: createVNode(ExclamationCircleOutlined),
        content: '确认要删除所选中的记录吗？',
        okText: '确认',
        onOk () {
          return new Promise((resolve, reject)=>{
            deleteService({ids: options.selectedKeys, message: '册除数据'}).then(res=>{
              message.success(res.msg)
              options.pageAction.run() // 刷新记录
              resolve()
            }).catch(()=>{ 
              console.info('册除异常')
              reject()
            })
          })
        },
        cancelText: '取消'
      })
    } else {
      message.warning('至少选中一项进行删除操作')
    }
  }

  // 审核（批准或拒绝 ）
  const auditEvent = () => {
    if (options.selectedKeys.length > 0) {
      Modal.confirm({
        title: '审批确认?',
        centered: true,
        closable: true,
        icon: createVNode(ExclamationCircleOutlined),
        content: createVNode('div', {}, [
          createVNode('div', { style: 'color: red' }, '请选择审批类型和审核批意见'),
          createVNode('div', { class: 'radio-label' },
            [
              createVNode('input', {
                id: 'd-approve',
                type: 'radio',
                name: 'color',
                checked: true,
                onClick: () => auditState.action = 'approve'
              // directives: [{ name: 'model', value: auditState.action}]
              }),
              createVNode('label', { for: 'd-approve' }, '通过 [Approve]')
            ]),
          createVNode('div', { class: 'radio-label red' },
            [
              createVNode('input', {
                id: 'd-reject',
                type: 'radio',
                name: 'color',
                onClick: () => auditState.action = 'reject'
              }),
              createVNode('label', { for: 'd-reject' }, '拒绝 [Reject]')
            ]),
          createVNode('textarea', {
            placeholder: '审批意见',
            class: 'ant-input',
            style: 'margin: 10px 0px',
            value: auditState.reason,
            onInput: event => { auditState.reason = event.target.value }
          })]),
        okText: '确定',
        onOk: async () => {
          if (auditState.reason!= '' && auditState.reason.length > 0) {
            auditState.selectedKeys = options.selectedKeys
            try{
              const ret = await options.auditService(auditState)
              if (ret.code == 0) {
                options.pageAction.refresh() // 刷新记录
                message.success(ret.msg)
              } else {
                message.error(ret.msg)
              }
              return Promise.resolve('审核成功')
            }catch(e) {
              message.error(e)
              console.log('Oops errors!')
            }
          } else {
            message.error('请输入审核意见')
            return Promise.reject()
          }
        },
        cancelText: '取消'
      })
    } else {
      message.warning('至少选中一项进行审批操作')
    }
  }

  // 确认
  const confirmEvent = () => {
    if(!confirmService) {
      message.error('还未设置处理接口')
      return 
    }
    if (options.selectedKeys.length > 0) {
      Modal.confirm({
        title: '审核确认?',
        icon: createVNode(ExclamationCircleOutlined),
        content: '确认要审核所选中的记录吗？',
        okText: '确认',
        onOk: async () => {
          try {
            const ret = await confirmService({ids: options.selectedKeys})
            console.info(ret)
            if (ret.code == 0) {
              options.pageAction.refresh() // 刷新记录
              message.success(ret.msg)
            } else {
              message.error(ret.msg)
            }
          } catch(e) {
            message.error(e)
            console.log('Oops errors!', e)
            return Promise.reject()
          }
        },
        cancelText: '取消'
      })
    } else {
      message.warning('至少选中一项进行审核操作')
    }
  }
  // 执行 execute.call([Promise方法名], 参数1, 参数2,.... )
  const execute = ()=>{
    this(...arguments).then(res=>{
      if(res.code == 0) {
        message.success(res.msg)
        pageAction.run() // 刷新记录
      }else{
        message.warning(res.msg)
      }
    }).catch(err=>{
      console.error(err)
    })
  }
  // 执行
  const executeCommand = (func, param)=>{
    func(param).then(res=>{
      if(res.code == 0) {
        message.success(res.msg)
        pageAction.refresh() // 刷新记录
      }else{
        message.warning(res.msg)
      }
    })
  }
  return {
    addEvent,
    editEvent,
    deleteEvent,
    auditEvent,
    confirmEvent,
    viewEvent,
    executeCommand,  // 公共执行方法
    execute, // 同上
    AllEvent: { // 所有事件
      addEvent, editEvent, deleteEvent, auditEvent, confirmEvent
    }
  }
}
